<?php defined('SYSPATH') or die('No direct script access.');
/**
 * GNU Social Hook
 *
 * PHP version 5
 * LICENSE: This source file is subject to AGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/licenses/agpl.html
 * @author	   Omar Vega Ramos <ovruni@gnu.org.pe> 
 * @copyright      (c) 2012 - 2016 Omar Vega Ramos
 * @license	   http://www.gnu.org/licenses/agpl.html GNU Affero General Public License (AGPL) 
 */

class gnusocial {

	protected $username;
	protected $password;
	protected $endpoint;
	
	/**
	 * Registers the main event add method
	 */
	public function __construct()
	{
		// Hook into routing
		Event::add('system.pre_controller', array($this, 'add'));
		
		// Set variables
		$this->username = Kohana::config('gnusocial.username');
		$this->password = Kohana::config('gnusocial.password');
		$this->endpoint = Kohana::config('gnusocial.endpoint');
	}
	
	/**
	 * Adds all the events to the main Ushahidi application
	 */
	public function add()
	{
		// Only add the events if we are on that controller
		if (Router::$controller == 'reports' AND Router::$method == 'index') {
			Event::add('ushahidi_action.report_approve', array($this, '_update_gnusocial'));
		}
		
		if (Router::$controller == 'reports' AND Router::$method == 'edit') {
			Event::add('ushahidi_action.report_edit', array($this, '_update_gnusocial'));
		}
	}
	
	public function _update_gnusocial()
	{
		// Access the report approved
		$update = Event::$data;
		
		if ($update->incident_active == 1) {
			$title = $this->_truncate(urldecode($update->incident_title));
			$link = url::base().'reports/view/'.$update->id;
			$short_link = $this->_ur1Shorten($link);
			
			// If we can't get ur1.ca to work, try again later
			if (empty($short_link)) {
				print "\nUnable to get short url for '$title' from ur1.ca. Skipping for now.\n\n";
				continue;
			}
			
			$status = "$title $short_link";
			$this->_post($status);
		}
	}
	
	/**
	 * Truncated the title
	 *
	 * @param   string   title
	 * @return  string   title truncated to 100 characters
	 */
	private function _truncate($str)
	{
		if (strlen($str) > 100) {
			// truncate at 100 chars
			$str = substr($str, 0, 100) . '...';
		}
		
		return trim(htmlspecialchars_decode($str));
	}
	
	/**
	 * Shortening the url
	 *
	 * @param   string   url
	 * @return  string   url short
	 */
	private function _ur1Shorten($url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, "ur1shorten");
		curl_setopt($ch, CURLOPT_URL,"http://ur1.ca");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, "longurl=$url");
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10);
		$html = curl_exec($ch);
		
		if (!$html) {
			printf("url1shorten - cURL error: %s\n", curl_error($ch));
			curl_close($ch);
			return NULL;
		}
		
		curl_close($ch);
		
		$dom = new DOMDocument();
		@$dom->loadHTML($html);
		$xpath = new DOMXPath($dom);
		$hrefs = $xpath->evaluate("/html/body/p[@class='success']/a");
		
		return $hrefs->item(0)->getAttribute('href');
	}
	
	/**
	 * Send report to GNU social instance
	 *
	 * @param   string   text to status
	 * @return  true
	 */
	private function _post($status)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_USERAGENT, "ushahidi");
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FAILONERROR, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $this->endpoint);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,
                array('status' => $status, 'source' => 'ushahidi'));
		curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
		
		$buffer = curl_exec($ch);
		
		if (!$buffer) {
			printf("cURL error: %s\n", curl_error($ch));
			curl_close($ch);
			return false;
		}
		
		curl_close($ch);
		
		return true;
	}
}

new gnusocial;
